package com.panopset.io;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.panopset.compat.Logz;
import com.panopset.compat.Strings;

public class FileRewriter {

	private final LineProcessor lp;
	
	public FileRewriter(final LineProcessor lineProcessor) {
		lp = lineProcessor;
	}
	
	public void process(final File file) {
        boolean changed = false;
        List<String> lines = new TextFileList(file).getLines();
        List<String> processedLines = new ArrayList<String>();
        for (String line : lines) {
        	String newLine = lp.process(line);
            processedLines.add(newLine);
            if (!newLine.equals(line)) {
                changed = true;
            }
        }
        int numberOfLines = processedLines.size();
        List<String> trimmed = Strings.toList(Strings
                .trimTrailingEmptyLines(Strings.toArray(processedLines)));
        if (trimmed.size() == numberOfLines && !changed) {
            Logz.dspmsg("Skipping unchanged file "
                    + new Filez().getCanonicalPath(file));
            return;
        }
        Logz.dspmsg("Updating file " + new Filez().getCanonicalPath(file));
        new FileTextList(trimmed).save(file);

	}

	public interface LineProcessor {
		String process(String line);
	}
}
